package person.tavion.transaction.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 测试死信消息的
 */
@Service
public class UserConsumerService {
    @KafkaListener(topics = {"myUser"},groupId = "myUserGroup", containerFactory="kafkaListenerContainerFactory")
//    public void kafkaListener(String message){
    // 批量消费
    public void kafkaListener(List<ConsumerRecord<String, String>> recordList){
        System.out.println("消费列表："+recordList.size());
        for (ConsumerRecord<String, String> consumerRecord : recordList) {
            kafkaListener(consumerRecord);
        }

    }
    // 单次消费
    public void kafkaListener(ConsumerRecord<String, String> record){
        String key = record.key().toString();
        String value = record.value().toString();
        System.out.println(record.offset()+" \t "+key+" \t "+ value);
        if(value.contains("abc")){
            System.out.println("存在消费abc");
            // 这里报错，就会把消息丢到死信队列中。
            throw new RuntimeException("存在消费abc");
        }
    }

    /**
     * 拉取死信消息
     * @param recordList
     */
    @KafkaListener(topics = {"myUser.DLT"},groupId = "myUserGroup.DLT", containerFactory="kafkaListenerContainerFactory")
    public void kafkaDLTListener(List<ConsumerRecord<String, String>> recordList){
        System.out.println("死信消费列表："+recordList.size());
        for (ConsumerRecord<String, String> consumerRecord : recordList) {
            kafkaDLTListener(consumerRecord);
        }

    }
    // 单次消费
    public void kafkaDLTListener(ConsumerRecord<String, String> record){
        String key = record.key().toString();
        String value = record.value().toString();
        System.out.println(record.offset()+" \t "+key+" \t "+ value);
        System.out.println("消费死信队列完成");
    }
}
